package com.cskaoyan.javase.network._2tcp._v3;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * 一个服务端处理客户端连接的任务
 * @since 15:58
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class ConnectTask implements Runnable {
    // 获取服务端的ServerSocket对象
    private Socket socket;

    public ConnectTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        while (true) {
            // 从Socket连接中获取输入流,读客户端发送的消息
            byte[] buf = new byte[1024];
            try {
                InputStream in = socket.getInputStream();
                int readCount = in.read(buf);
                String msg = new String(buf, 0, readCount);
                System.out.println(socket.getRemoteSocketAddress() + "发来的消息是:" + msg);
            } catch (SocketException e) {
                // 说明客户端突然中断
                System.out.println(socket.getRemoteSocketAddress() + "已经断开了!");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
